package tag

import (
	"encoding/base64"
	"encoding/json"
	"fmt"
	"hash/fnv"
	"time"
)

func NewTagSet() *TagSet {
	return &TagSet{
		Items: []*Tag{},
	}
}

type TagSet struct {
	Total int64  `json:"total"`
	Items []*Tag `json:"items"`
}

func (s *TagSet) String() string {
	dj, err := json.Marshal(s)
	if err != nil {
		panic(err)
	}
	return string(dj)
}

func NewTag(req *CreateTagRequest) (*Tag, error) {
	if req == nil {
		return nil, fmt.Errorf("req is nil")
	}

	if err := req.Validate(); err != nil {
		return nil, err
	}

	// 短hash算法, 不适于内容hash
	h := fnv.New32a()
	_, err := h.Write([]byte(fmt.Sprintf("%d.%s.%s", req.BlogId, req.Key, req.Value)))
	if err != nil {
		return nil, err
	}

	return &Tag{
		Id:               base64.StdEncoding.EncodeToString(h.Sum(nil)),
		CreateTagRequest: req,
		CreatedAt:        time.Now().Unix(),
	}, nil
}

type Tag struct {
	// tag id, Hash(文章+标签key+标签Value)
	Id string `json:"id"`
	*CreateTagRequest
	CreatedAt int64 `json:"created_at"`
}
